﻿using UnityEngine;
using System.Collections;

public class Quit : MonoBehaviour {

    public string onQuitScene = "networkingMainMenu";
    private bool quitPopupShowing = false;
    private bool escapeHandled = false;

    private Rect quitWindowRect = new Rect(0, 0, 0, 0);

	// Use this for initialization
	void Start () {
        quitWindowRect = new Rect(Screen.width / 2 - 100, Screen.height / 2 - 40, 200, 90);
	}
	
	// Update is called once per frame
	void Update () {
        escapeHandled = false;
	}

    void OnGUI()
    {
        bool popupChanged = false;
        if (Event.current.type == EventType.keyDown && Event.current.keyCode == KeyCode.Escape && !escapeHandled)
        {
            print("Escape handled by main GUI");
            quitPopupShowing = !quitPopupShowing;
            popupChanged = true;
            escapeHandled = true;
        }

        if (quitPopupShowing)
        {
            // TODO: Show the quit window and all that
            quitWindowRect = GUI.Window(1, quitWindowRect, OnQuitWindowGUI, "Quit");
            if (popupChanged) GUI.FocusWindow(1);
        }
    }

    void OnQuitWindowGUI(int windowId)
    {
        GUI.Label(new Rect(10, 25, 180, 20), "Quit game and return to menu?");

        if (GUI.Button(new Rect(15, 55, 80, 30), "Yes"))
        {
            GameObject.Find("GameController").GetComponent<NetworkDungeonController>().OnGameQuit();
            Application.LoadLevel(onQuitScene);
        }

        if (GUI.Button(new Rect(105, 55, 80, 30), "No"))
        {
            quitPopupShowing = false;
        }

    }
}
